package com.zzqstart.vod.service.impl;


import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.netflix.client.ClientException;
import com.zzqstart.servicebase.exceptionhandler.CateException;
import com.zzqstart.vod.service.VodService;
import com.zzqstart.vod.utils.ConstantPropertiesUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.zzqstart.vod.utils.InitVodClient.initVodClient;

/**
 * ClassName: VodServiceImpl
 * Package: com.atguigu.vod.service.impl
 * Description:
 *
 * @Author zzqstart
 * @Create 2023-02-27 13:36
 * @Version 1.0
 */
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String saveVideo(MultipartFile file) {
        InputStream inputStream = null;
        try {
            String fileName = file.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf("."));
            inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
            return response.getVideoId();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new CateException(20001,"上传失败");
    }

    @Override
    public void deleteVideoById(List<String> videoIdList) {
        try {
            DefaultAcsClient client = initVodClient(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            String videoIdString = StringUtils.join(videoIdList, ",");
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(videoIdString);
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CateException(20001,"删除视频失败");
        }
    }

    @Override
    public void deleteAllVideoByCourseId(String courseId) {

    }


}
